# -*- coding: utf-8 -*-
import json
from datetime import datetime, timedelta
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import build_sha1_order_id, md5, short_uuid
from zc_core.util.common import parse_time
from sdszfcg.items import sdszfcgSupplier


def parse_sku(response):
    meta = response.meta
    catalog_id = meta.get('catalogId')
    catalog_name = meta.get('catalogName')

    content = json.loads(response.text)
    coll = content.get('page', {}).get('list', [])
    sku_list = list()
    if coll and len(coll) > 0:
        meta = response.meta
        batch_no = meta.get('batchNo')
        catalog_hepler = CatalogHelper()
        for value in coll:
            entity = ItemData()
            entity['batchNo'] = batch_no
            entity['skuId'] = str(value.get("id", ''))
            entity['supplierId'] = str(value.get("supplierId", ''))
            entity['supplierName'] = value.get("supplierName", '')
            entity['catalog3Id'] = catalog_id
            entity['catalog3Name'] = catalog_name
            # entity['catalog3Id'] = str(value.get('catalogId', ''))
            # entity['catalog3Name'] = str(value.get('catalogName', ''))
            entity['brandName'] = value.get('brandName', '')
            entity['brandId'] = str(value.get('brandId', ''))
            entity['soldCount'] = value.get('sales')
            entity['skuImg'] = value.get('coverUrl')
            entity['skuName'] = value.get('name', '')
            entity['originPrice'] = value.get('marketPrice', '')
            entity['salePrice'] = value.get('price', '')
            entity['barCode'] = value.get('upc', '')
            # 有的unit填的公司名字
            # entity['unit'] = value.get('unit', '')
            entity['brandModel'] = value.get('model', '')
            try:
                catalog_hepler.fill(entity)
            except Exception as e:
                pass
            sku_list.append(entity)
    return sku_list


def parse_item_data(response):
    cat_helper = CatalogHelper()
    item_data = json.loads(response.text)
    if not item_data:
        return None
    meta = response.meta
    batch_no = meta.get('batchNo')

    item = ItemData()
    item['batchNo'] = batch_no
    item['skuId'] = str(item_data.get("id"))
    item['brandId'] = str(item_data.get("brandId"))
    item['brandModel'] = item_data.get("model")

    item['brandName'] = item_data.get("brandName")
    item['catalog3Id'] = str(item_data.get("catalogId"))
    item['catalog3Name'] = item_data.get("catalogName")

    cat_helper.fill(item)
    item['originPrice'] = item_data.get("marketPrice")
    item['salePrice'] = item_data.get("price")
    item['skuImg'] = item_data.get("coverUrl")
    item['skuName'] = item_data.get("name")
    item['soldCount'] = item_data.get("sales")
    item['supplierId'] = str(item_data.get("supplierId"))
    item['supplierName'] = item_data.get("supplierName")

    sp_sku_id = item_data.get("sku")
    if sp_sku_id:
        item['supplierSkuId'] = sp_sku_id
        plat_code = None
        if item['supplierId'] == '353' or '得力' in item['supplierName']:
            plat_code = 'deli'
        item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)
    item['supplierSkuLink'] = item_data.get("factoryURL", '')
    item['unit'] = item_data.get("unit", '')

    if item_data.get("updatedAt"):
        item['onSaleTime'] = parse_time(item_data.get("updatedAt"))
    item['genTime'] = datetime.utcnow()

    return item


def parse_catalog(response):
    if not response.text:
        return None
    cat_json = json.loads(response.text)
    cats = list()
    for cata1 in cat_json:
        entity1 = build_catalog(cata1, 1)
        cats.append(entity1)
        childs1 = cata1.get('children')
        if childs1:
            for cata2 in childs1:
                entity2 = build_catalog(cata2, 2)
                cats.append(entity2)
                childs2 = cata2.get('children')
                if childs2:
                    for cata3 in childs2:
                        entity3 = build_catalog(cata3, 3)
                        cats.append(entity3)
    return cats


def build_catalog(cat, level):
    entity = Catalog()

    entity['catalogId'] = str(cat.get('id'))
    entity['catalogName'] = cat.get('name') or cat.get('catalogName')
    entity['parentId'] = str(cat.get('parentId'))
    entity['level'] = level
    if entity['level'] == 3:
        link_url = str(cat.get('linkUrl'))
        if link_url not in ['None', None]:
            entity['catalogId'] = link_url.split("?c_")[1].split("|")[0]
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_order(response):
    order_json = json.loads(response.text).get('data', {})
    meta = response.meta
    sku_id = meta.get("skuId")
    supplier_id = meta.get("supplierId")
    supplier_name = meta.get("supplierName")
    orders = list()
    batch_no = meta.get('batchNo')

    prev_order = None
    same_order_no = 1
    for order in order_json.get("list"):
        entity = OrderItem()
        entity["amount"] = order.get("subtotal")
        entity["batchNo"] = batch_no
        entity["count"] = order.get("num")
        entity["deptId"] = md5(order.get("purchaserName"))
        entity["orderDept"] = order.get("purchaserName")
        entity["orderTime"] = parse_time(order.get("completedAt"))
        entity["skuId"] = sku_id
        entity["supplierId"] = supplier_id
        entity["supplierName"] = supplier_name
        order_timestamp = order.get("completedAt")
        if prev_order and prev_order.equals(entity):
            same_order_no = same_order_no + 1
        else:
            same_order_no = 1
        addition = {
            'sameOrderNo': same_order_no,
            'orderTimeStr': order_timestamp,
        }
        sha1_id = build_sha1_order_id(entity, addition)
        entity['id'] = sha1_id
        entity['orderId'] = sha1_id
        entity["genTime"] = datetime.utcnow()
        orders.append(entity)
        prev_order = entity
    return orders


# 解析group关系
def parse_group(response):
    meta = response.meta
    batch_no = meta.get("batchNo")
    sku_id = meta.get('skuId')
    rs = json.loads(response.text)
    spu_id = short_uuid()
    group = ItemGroup()
    if rs and isinstance(rs, list):
        ids = list()
        group['skuIdList'] = ids
        group['spuId'] = spu_id
        group['batchNo'] = batch_no
        group['skuId'] = sku_id
        for same_sku in rs:
            same_sku_id = str(same_sku.get("id"))
            ids.append(same_sku_id)
    return group


# 供应商
def parse_supplier(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    json_data = json.loads(response.text)
    supplier_list = []
    for data in json_data.get('data', {}).get('data', []):
        sp = sdszfcgSupplier()
        sp['id'] = str(data.get('id', ''))
        sp['name'] = data.get('name', '')
        sp['supplierLink'] = data.get('shopStoreUrl', '')
        sp['batchNo'] = batch_no
        supplier_list.append(sp)
    return supplier_list


# 供应商页数
def parse_supplier_page(response):
    json_data = json.loads(response.text)
    pages = json_data.get('data', {}).get('pages', 1)
    return int(pages)


# 供应商分页
def parse_supplier_catalog(response):
    cat_json = json.loads(response.text)
    cats = list()
    for cata1 in cat_json:
        cat1_id = str(cata1.get('id', ''))
        cat1_name = cata1.get('name')
        entity1 = build_supplier_catalog(cat1_id, cat1_name, '', 1)
        cats.append(entity1)
        childs1 = cata1.get('children')
        if childs1:
            for cata2 in childs1:
                cat2_id = str(cata2.get('id', ''))
                cat2_name = cata2.get('name')
                entity2 = build_supplier_catalog(cat2_id, cat2_name, cat1_id, 2)
                cats.append(entity2)
                childs2 = cata2.get('children')
                if childs2:
                    for cata3 in childs2:
                        # cat3_id = str(cata3.get('id', ''))
                        cat3_id = str(cata3.get('platformCatalogId', ''))
                        cat3_name = cata3.get('name')
                        entity3 = build_supplier_catalog(cat3_id, cat3_name, cat2_id, 3)
                        cats.append(entity3)
    return cats


def build_supplier_catalog(id, name, parent_id, level):
    entity = Catalog()

    entity['catalogId'] = id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    entity['linkable'] = 0
    return entity
